package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.BusinessException;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.EmpQueryParam;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public PageResult<Clazz> page(EmpQueryParam empQueryParam) {

        //1.设置分页参数（pageHelper）
        PageHelper.startPage(empQueryParam.getPage(), empQueryParam.getPageSize());
//        Integer strat = (empQueryParam.getPage() - 1) * empQueryParam.getPageSize();
//        empQueryParam.setPage(strat);
        List<Clazz>  clazzList = clazzMapper.list(empQueryParam);
        LocalDate now = LocalDate.now();
        for (Clazz clazz : clazzList) {
            LocalDate begin = clazz.getBeginDate();
            LocalDate end = clazz.getEndDate();

            if (now.isBefore(begin)){
                clazz.setStatus("未开班");
            }
            else{
                if (now.isAfter(end)){
                    clazz.setStatus("已结课");
                }
                else {
                    clazz.setStatus("已开班");
                }
            }
        }
        Page<Clazz> p = (Page<Clazz>) clazzList;
        return new PageResult(p.getTotal(), p.getResult());
    }
    @Override
    public void deleteById(Integer id) throws BusinessException {
        Integer count  = studentMapper.countByClazzId(id);

        if (count != 0){
            throw new BusinessException("班级下有学员, 不能直接删除~");
        }
        else {
            clazzMapper.deleteById(id);
        }
    }

    @Override
    public void addClazz(Clazz clazz) {
        //添加基本数据
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());

        clazzMapper.addClazz(clazz);

    }
    @Override
    public Clazz getInfo(Integer id){
        Clazz clazz = clazzMapper.getInfo(id);
        return clazz;
    }

    @Override
    public void update(Clazz clazz) {
        //补充数据
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }

    @Override
    public ArrayList<Clazz> getAllClass() {
        ArrayList<Clazz> clazzes = clazzMapper.getAllClazz();
        return clazzes;
    }


}